package com.ins1st.annotation.aspect;

import com.ins1st.annotation.DataSource;
import com.ins1st.core.config.druid.multi.DBTypeEnum;
import com.ins1st.core.config.druid.multi.DbContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;


/**
 * 数据源切换拦截器
 *
 * @author sun
 */
@Aspect
@Component
@Order(value = -100)
public class DataSourceAspect {

    @Pointcut("@annotation(com.ins1st.annotation.DataSource)")
    private void master() {
    }

    @Pointcut("@annotation(com.ins1st.annotation.DataSource)")
    private void slave() {
    }

    @Before("master()")
    public void beforeMaster(JoinPoint joinPoint) {
        handle(joinPoint);
    }

    @Before("slave()")
    public void beforeSlave(JoinPoint joinPoint) {
        handle(joinPoint);

    }

    private void handle(JoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        DataSource dataSource = method.getAnnotation(DataSource.class);
        String value = dataSource.db();
        if (StringUtils.isNotBlank(value)) {
            for (DBTypeEnum type : DBTypeEnum.values()) {
                if (type.getValue().equals(value)) {
                    DbContextHolder.setDbType(type);
                }
            }
        }
    }

}
